package by.grsu.transport.service.impl;

import org.apache.log4j.Logger;

import by.grsu.transport.converter.UserConverter;
import by.grsu.transport.exception.UserExistException;
import by.grsu.transport.model.User;
import by.grsu.transport.persistence.dao.DaoManager;
import by.grsu.transport.persistence.dao.UserDao;
import by.grsu.transport.persistence.dao.base.ConnectionBehavior;
import by.grsu.transport.persistence.dao.base.DaoCommand;
import by.grsu.transport.service.RegistrationService;

public class RegistrationServiceImpl implements RegistrationService {

	private static final Logger logger = Logger.getLogger(RegistrationServiceImpl.class);
	DaoManager daoManager;

	public RegistrationServiceImpl(DaoManager daoManager) {
		this.daoManager = daoManager;
	}

	@Override
	public void registerUser(final User user) throws UserExistException {
		
		daoManager.command(new DaoCommand() {
			
			@Override
			public Object execute(DaoManager daoManager)  {
				UserDao userDao = daoManager.getDao(UserDao.class);
				if (userDao.getUser(user.getLogin()) == null) {
					userDao.insert(UserConverter.getInstance().modelToEntity(user));
				}else{
					logger.error("Impossible to register new user. User with such login already exist!");
				}
				return null;
			}
		}, ConnectionBehavior.CLOSE);
		
		
		

	}

}
